package com.adv.crm.controller;

import com.adv.crm.beans.AccountQueryBean;
import com.adv.crm.services.AccountService;
import com.adv.crm.services.ExcelService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Arrays;

/**
 * Created by 16978 on 2016/6/18.
 */
@Controller
@RequestMapping("account")
public class DataController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private ExcelService excelService;



    @RequestMapping("data")
    public String dataView() {
        return "data";
    }

    @RequestMapping(value = "import",method = RequestMethod.POST)
    public String importData(@RequestParam(value = "account-file",required = false)MultipartFile file) {
        try {
            InputStream is = file.getInputStream();
           excelService.readExcel(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "import";
    }

    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportData(HttpServletResponse response,String accountNameArea, String accountIdArea, AccountQueryBean bean) {

        ServletOutputStream out = null;
        XSSFWorkbook wb = null;
        try {
            if (StringUtils.isNotBlank(accountIdArea)) {
                bean.setAccountIds(Arrays.asList(accountIdArea.split("\\r\\n")));
            }
            if (StringUtils.isNotBlank(accountNameArea)) {
                bean.setAccountNames(Arrays.asList(accountNameArea.split("\\r\\n")));
            }
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "application/vnd.ms-excel;charset=UTF-8");
            String newFileName = URLEncoder.encode("报价.xlsx", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + newFileName);
            out = response.getOutputStream();
            wb = excelService.exportDataToExcel(bean);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    wb.write(out);
                    out.close();
                    wb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return "import";
    }

}
